<template>
  <div
    ref="pagination"
    class="flex justify-center items-center gap-2 text-sm py-2 dark:bg-gray-900 shadow"
  >
    <!-- 上一页 -->
    <button
      :disabled="currentPage === 1"
      @click="prevPage"
      class="text-gray-600 dark:text-gray-400 hover:text-blue-500 disabled:text-gray-300 disabled:cursor-not-allowed transition-all"
    >
      ←
    </button>

    <!-- 页码范围 -->
    <span class="text-gray-800 dark:text-gray-300">
      {{ currentPage }} / {{ totalPages }}
    </span>

    <!-- 下一页 -->
    <button
      :disabled="currentPage === totalPages"
      @click="nextPage"
      class="text-gray-600 dark:text-gray-400 hover:text-blue-500 disabled:text-gray-300 disabled:cursor-not-allowed transition-all"
    >
      →
    </button>
  </div>
</template>

<script setup>
import { ref, defineProps, defineEmits } from 'vue'

const props = defineProps({
  page: {
    type: Number,
    default: 1
  },
  totalPages: {
    type: Number,
    required: true
  },
  scrollTo: {
    type: Number,
    default: 0
  }
})

// 定义事件发射
const emit = defineEmits(['update:page', 'page-changed'])

const pagination = ref(null) // 用来获取分页器元素

// 当前页码
const currentPage = ref(props.page)

// 滚动到页面顶部
const scrollToTop = () => {
  window.scrollTo({
    top: props.scrollTo,
    behavior: 'smooth' // 平滑滚动
  })
}

// 上一页
const prevPage = () => {
  if (currentPage.value > 1) {
    currentPage.value--
    emit('update:page', currentPage.value) // 发射绑定的页面更新事件
    emit('page-changed', currentPage.value) // 触发额外事件，供父组件使用
    scrollToTop() // 滚动到顶部
  }
}

// 下一页
const nextPage = () => {
  if (currentPage.value < props.totalPages) {
    currentPage.value++
    emit('update:page', currentPage.value) // 发射绑定的页面更新事件
    emit('page-changed', currentPage.value) // 触发额外事件，供父组件使用
    scrollToTop() // 滚动到顶部
  }
}
</script>
